package com.thysdy.flowable.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.thysdy.flowable.common.PersonInfoUtil;
import com.thysdy.flowable.entity.*;
import com.thysdy.flowable.enums.CodeEnum;
import com.thysdy.flowable.exception.MyException;
import com.thysdy.flowable.flowable.BaseProcessService;
import com.thysdy.flowable.mapper.TaskInfoMapper;
import com.thysdy.flowable.mapper.UserMapper;
import com.thysdy.flowable.service.impl.FlowablePersonInfoService;
import com.thysdy.flowable.vo.ProcessVariablesVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskService extends BaseProcessService {
    @Resource
    TaskInfoMapper taskInfoMapper;
    @Resource
    CommonService commonService;
    @Resource
    UserMapper userMapper;
    @Resource
    IProcessassignConfigService processassignConfigService;
    @Resource
    IActRuIdentitylinkService ruIdentitylinkService;
    @Autowired
    FlowablePersonInfoService personInfoService;


    public List<String> taskQueryByName(String processDefinitionKey, String taskName) {
        return taskService.createTaskQuery().processDefinitionKey(processDefinitionKey).taskName(taskName).list().stream().map(Task::getProcessInstanceId).collect(Collectors.toList());
    }

    public String getNowTaskAssignee(RequestVo requestVo) {
        if (null != requestVo && ((StringUtils.isNotBlank(requestVo.getBusinessKey()) && StringUtils.isNotBlank(requestVo.getProcessDefinitionKey())) || (StringUtils.isNotBlank(requestVo.getProcessInstanceId())))) {
            Task myTask = null;
            if (StringUtils.isNotBlank(requestVo.getProcessInstanceId())) {
                String instanceId = requestVo.getProcessInstanceId();
                myTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
            } else {
                String businessKey = requestVo.getBusinessKey();
                String definitionKey = requestVo.getProcessDefinitionKey();
                List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).processDefinitionKey(definitionKey).orderByTaskCreateTime().desc().list();
                if (null != tasks && !tasks.isEmpty()) {
                    myTask = tasks.get(0);
                }
            }
            if (null != myTask) {
                return myTask.getAssignee();
            }
        }
        return null;
    }

    public UserTaskVo getNowTaskBasicInfo(RequestVo requestVo) {
        if (null != requestVo && ((StringUtils.isNotBlank(requestVo.getBusinessKey()) && StringUtils.isNotBlank(requestVo.getProcessDefinitionKey())) || (StringUtils.isNotBlank(requestVo.getProcessInstanceId())))) {
            Task myTask = null;
            if (StringUtils.isNotBlank(requestVo.getProcessInstanceId())) {
                String instanceId = requestVo.getProcessInstanceId();
                myTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
            } else {
                String businessKey = requestVo.getBusinessKey();
                String definitionKey = requestVo.getProcessDefinitionKey();
                List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).processDefinitionKey(definitionKey).orderByTaskCreateTime().desc().list();
                if (null != tasks && !tasks.isEmpty()) {
                    myTask = tasks.get(0);
                }
            }
            if (null != myTask) {
                UserTaskVo userTaskVo = new UserTaskVo();
                userTaskVo.setId(myTask.getId());
                userTaskVo.setKey(myTask.getTaskDefinitionKey());
                userTaskVo.setName(myTask.getName());
                userTaskVo.setProcessInstanceId(myTask.getProcessInstanceId());

                Map<String, Object> processVariables = runtimeService.getVariables(myTask.getProcessInstanceId());
                userTaskVo.setVariables(processVariables);

                String assignee = myTask.getAssignee();
                userTaskVo.setLastAssignUser(assignee);
                return userTaskVo;
            }
        }
        return null;
    }

    public UserTaskVo getNowTaskInfo(RequestVo requestVo) throws MyException {
        try {
            if (null != requestVo && ((StringUtils.isNotBlank(requestVo.getBusinessKey()) && StringUtils.isNotBlank(requestVo.getProcessDefinitionKey())) || (StringUtils.isNotBlank(requestVo.getProcessInstanceId())))) {
                Task myTask = null;
                if (StringUtils.isNotBlank(requestVo.getProcessInstanceId())) {
                    String instanceId = requestVo.getProcessInstanceId();
                    myTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
                } else {
                    String businessKey = requestVo.getBusinessKey();
                    String definitionKey = requestVo.getProcessDefinitionKey();
                    List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).processDefinitionKey(definitionKey).orderByTaskCreateTime().desc().list();
                    if (null != tasks && !tasks.isEmpty()) {
                        myTask = tasks.get(0);
                    }
                }
                if (null != myTask) {
                    UserTaskVo userTaskVo = new UserTaskVo();
                    userTaskVo.setId(myTask.getId());
                    userTaskVo.setKey(myTask.getTaskDefinitionKey());
                    userTaskVo.setName(myTask.getName());
                    userTaskVo.setProcessInstanceId(myTask.getProcessInstanceId());
                    String assignee = myTask.getAssignee();
                    userTaskVo.setLastAssignUser(assignee);
                    List<String> assignUsers = new ArrayList<>();
//                    List<String> assignGroups = new ArrayList<>();
                    if (StringUtils.isNotBlank(assignee)) {
                        assignUsers.add(assignee);
                    }
                    String instanceId = myTask.getProcessInstanceId();
                    LambdaQueryWrapper<ActRuIdentitylink> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(ActRuIdentitylink::getProcInstId, instanceId);
                    queryWrapper.ne(ActRuIdentitylink::getType, "starter");
                    List<ActRuIdentitylink> ruIdentitylinks = ruIdentitylinkService.list(queryWrapper);

                    if (null != ruIdentitylinks) {
                        for (ActRuIdentitylink info : ruIdentitylinks) {
                            if (StringUtils.isNotBlank(info.getUserId())) {
                                assignUsers.add(info.getUserId());
                            }
//                            if (StringUtils.isNotBlank(info.getGroupId())) {
//                                assignGroups.add(info.getGroupId());
//                            }
                        }
                    }
                    //审核人去重
                    assignUsers = assignUsers.stream().collect(
                            Collectors.collectingAndThen(Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(x -> x))), ArrayList::new));
                    //查询审核人信息
                    if (!assignUsers.isEmpty()) {
                        List<User> users = userMapper.findUsersByIds(assignUsers);
                        userTaskVo.setAssignUsers(users);
                    }
                    return userTaskVo;
                } else {
                    return null;
                }
            } else {
                throw new MyException(CodeEnum.paramError);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>getNowTaskInfo error!", e);
            throw new MyException(CodeEnum.commonException);
        }
    }

    public PageEntity getMyTasks(ProcessInstanceQueryVo processQueryVo) throws MyException {
        List<TaskVo> tasks = new ArrayList<>();
        PageEntity pageEntity = null;
        try {
            Page<TaskVo> page = new Page<>(processQueryVo.getNowPage(), processQueryVo.getPageSize());
            IPage<TaskVo> taskPage = taskInfoMapper.getApplyingTasks(page, processQueryVo);
            tasks = taskPage.getRecords();
            for (TaskVo task : tasks) {
                Map<String, Object> processVariables = runtimeService.getVariables(task.getProcessInstanceId());
                task.setVariables(processVariables);
            }
            pageEntity = new PageEntity(taskPage.getTotal(), taskPage.getPages(), taskPage.getSize(), taskPage.getCurrent(), tasks);
        } catch (Exception e) {
            log.error("===>getMyTasks error!", e);
            e.printStackTrace();
            throw new MyException(CodeEnum.commonException);
        }
        return pageEntity;
    }

    /**
     * 获取我的已办任务
     *
     * @param processQueryVo
     * @return
     */
    public PageEntity getMyApplyedTasks(ProcessInstanceQueryVo processQueryVo) throws MyException {
        List<TaskVo> tasks = new ArrayList<>();
        PageEntity pageEntity = null;
        try {
            Page<TaskVo> page = new Page<>(processQueryVo.getNowPage(), processQueryVo.getPageSize());
            IPage<TaskVo> taskPage = taskInfoMapper.getMyApplyedTasks(page, processQueryVo);
            tasks = taskPage.getRecords();
            for (TaskVo task : tasks) {
                String instanceId = task.getProcessInstanceId();
                List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(instanceId).list();
                Map<String, Object> variables = new HashMap<>();
                for (int i = 0; i < list.size(); i++) {
                    HistoricVariableInstance historicVariableInstance = list.get(i);
                    String name = historicVariableInstance.getVariableName();
                    Object object = historicVariableInstance.getValue();
                    variables.put(name, object);
                }
                task.setVariables(variables);
            }
            pageEntity = new PageEntity(taskPage.getTotal(), taskPage.getPages(), taskPage.getSize(), taskPage.getCurrent(), tasks);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>getMyApplyedTasks error!", e);
            throw new MyException(CodeEnum.commonException);

        }
        return pageEntity;
    }

    /**
     * 执行任务
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String doTask(RequestVo request) throws MyException {
        try {
            log.info("doTask传参----->" + request);
            String personNameString = null;
            Task nextTask = null;
            List<String> users = new ArrayList<>();
            String message = request.getMessage();
            String userId = request.getUserCode();
            List<String> ids = request.getIds();
            String returnMessage = "执行成功!";
            Map<String, Object> variables = request.getVariables();
            Map<String, Object> localVariables = request.getLocalVariables();
            int successCount = 0;
            for (String id : ids) {
                Task task = taskService.createTaskQuery().taskId(id).singleResult();
                if (null != task) {
                    String instanceId = task.getProcessInstanceId();
                    Map<String, Map<String, List<String>>> globalAssignSettings = null;
                    List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(instanceId).list();
                    Map<String, Object> variable = new HashMap<>();
                    if (null != list && !list.isEmpty()) {
                        for (int i = 0; i < list.size(); i++) {
                            HistoricVariableInstance historicVariableInstance = list.get(i);
                            String name = historicVariableInstance.getVariableName();
                            Object object = historicVariableInstance.getValue();
                            variable.put(name, object);
                        }
                    }
                    try {
                        globalAssignSettings = (Map<String, Map<String, List<String>>>) variable.get("globalAssignSettings");
                    } catch (Exception e) {
                    }
                    //设置当前执行人
                    taskService.setAssignee(task.getId(), userId);
                    taskService.setVariablesLocal(task.getId(), localVariables);
                    //设置下一任务执行人
                    List<String> assignUsers = request.getAssignUsers();
                    List<String> assignGroups = request.getAssignGroups();
                    if (null != assignUsers && !assignUsers.isEmpty()) {
                        users.addAll(assignUsers);
                    }
                    if (null == variables) {
                        variables = new HashMap<>();
                    }
                    variables.put("assignUsers", assignUsers);
                    variables.put("assignGroups", assignGroups);
                    variables.put("latestUserId", userId);
                    //执行任务
                    taskService.complete(id, variables, localVariables);
                    if (users.isEmpty() && null != globalAssignSettings && !globalAssignSettings.isEmpty()) {
                        nextTask = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
                        if (null != nextTask) {
                            String taskKey = nextTask.getTaskDefinitionKey();
                            Map<String, List<String>> listMap = globalAssignSettings.get(taskKey);
                            if (null != listMap) {
                                List<String> nextTaskAssignUsers = listMap.get("assignUsers");
                                if (null != nextTaskAssignUsers) {
                                    users.addAll(nextTaskAssignUsers);
                                }
                            }
                        }
                    }

                    //添加审核人，审核组
                    commonService.addAssignUserOrGroup(request.getAssignUsers(), request.getAssignGroups(), globalAssignSettings, instanceId, nextTask);

                    //查询派发人
                    if (!users.isEmpty()) {
                        Map<String, ActIdUser> actIdUsers = personInfoService.getPersonInfoList(users);
                        if (null != actIdUsers) {
                            personNameString = PersonInfoUtil.getUserNameString(actIdUsers);
                        }

                    }
                    if (StringUtils.isNotBlank(message)) {
                        if (StringUtils.isNotBlank(personNameString)) {
                            message = message + "\n任务派发至: " + personNameString;
                        }
                    } else {
                        if (StringUtils.isNotBlank(personNameString)) {
                            message = "任务派发至: " + personNameString;
                        }
                    }
                    //添加审批记录

                    this.addComment(id, userId, instanceId,
                            CommentTypeEnum.SP.toString(), message);
                    successCount++;
                }

            }
            int failCount = ids.size() - successCount;
            if (failCount > 0) {
                if (successCount > 0) {
                    returnMessage = successCount + "个任务执行成功," + failCount + "个任务执行失败（任务已处理）！";
                } else {
                    returnMessage = "执行失败(任务已处理)!";
                }
            }
            return returnMessage;
        } catch (MyException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("do task error!", e);
            throw new MyException(CodeEnum.commonException);
        }
    }

    /**
     * 退回任务
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void rollback(RequestVo request) throws MyException {
        String target = request.getTarget();
        String[] t = target.split(",");
        String targetKey = t[0];
        String targetName = t[1];
        List<String> assignUsers = null;
        List<String> assignGroups = null;
        String assignUser = request.getAssignee();
        try {

            Task myTask = taskService.createTaskQuery().taskId(request.getTaskId()).singleResult();
            String instanceId = myTask.getProcessInstanceId();
            Map<String, Object> processVariables = runtimeService.getVariables(instanceId);
            ProcessVariablesVo variables = new Gson().fromJson(new Gson().toJson(processVariables), ProcessVariablesVo.class);
            if (StringUtils.isBlank(assignUser)) {
                if (null != variables && null != variables.getGlobalAssignSettings()) {
                    ProcessVariablesVo.TaskAssignSetting setting = variables.getGlobalAssignSettings().get(targetKey);
                    if (null != setting) {
                        assignUsers = setting.getAssignUsers();
                        assignGroups = setting.getAssignGroups();
                    }
                }
            }
            //根据目标任务key查询跳过表达式
            String processDefinitionId = taskInfoMapper.getProcessDefinitionIdByInstanceId(instanceId);
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            Process process = bpmnModel.getProcesses().get(0);
            Collection<UserTask> flowElements1 = process.findFlowElementsOfType(UserTask.class);
            for (UserTask userTask : flowElements1) {
                if (userTask.getId().equals(targetKey)) {
                    String assignee = userTask.getAssignee();
                    List<String> candidateUsers = userTask.getCandidateUsers();
                    List<String> candidateGroups = userTask.getCandidateGroups();
                    if (null == assignUser && null == assignee && candidateUsers.isEmpty() && candidateGroups.isEmpty() && (null == assignUsers || assignUsers.isEmpty()) && (null == assignGroups || assignGroups.isEmpty())) {
                        throw new MyException(30005, "该节点无审核人/审核组,不可退回!");
                    }
                    String skipExpression = userTask.getSkipExpression();
                    if (StringUtils.isNotBlank(skipExpression)) {
                        int index = skipExpression.lastIndexOf("}");
                        String eSring = skipExpression.substring(2, index);
                        processVariables.put(eSring, false);
                    }
                    break;
                }
            }

            String message = "申请退回到" + targetName;
            if (StringUtils.isNotBlank(request.getBackReason())) {
                message = message + "\n退回原因：" + request.getBackReason();
            }
            List<String> key = new ArrayList<>();
            key.add(myTask.getTaskDefinitionKey());
            processVariables.put("state", "退回");
            runtimeService.createChangeActivityStateBuilder()
                    .processInstanceId(instanceId)
                    .processVariables(processVariables)
                    .moveActivityIdsToSingleActivityId(key, targetKey)
                    .changeState();
            //退回给待办人
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(instanceId).list();
            List<String> finalAssignUsers = assignUsers;
            List<String> finalAssignGroups = assignGroups;
            //单实例节点退回
            if (tasks.size() == 1) {
                Task nowTask = tasks.get(0);
                if (StringUtils.isNotBlank(request.getAssignee())) {
                    taskService.setAssignee(nowTask.getId(), assignUser);
                } else {
                    if (null != finalAssignUsers && !finalAssignUsers.isEmpty()) {
                        finalAssignUsers.forEach(x -> taskService.addCandidateUser(nowTask.getId(), x));
                    }
                    if (null != finalAssignGroups && !finalAssignGroups.isEmpty()) {
                        finalAssignGroups.forEach(x -> taskService.addCandidateGroup(nowTask.getId(), x));
                    }
                }
            }
            //多实例节点退回
            List<String> assigneeList = (List<String>) processVariables.get("assigneeList");
            if (tasks.size() > 1 && !CollectionUtils.isEmpty(assigneeList)) {
                for (int a = 0; a < tasks.size(); a++) {
                    Task nowTask = tasks.get(a);
                    taskService.setAssignee(nowTask.getId(), assigneeList.get(a));
                }
            }
            this.addComment(request.getTaskId(), request.getUserCode(), instanceId,
                    CommentTypeEnum.TH.toString(), message);
        } catch (MyException e) {
            throw e;
        } catch (Exception e) {
            log.error("===>rollback error!", e);
            throw new MyException(CodeEnum.commonException);
        }
    }

    public List<FlowNodeVo> getBackNode(String processInstanceId) throws MyException {
        List<FlowNodeVo> datas = new ArrayList<>();
        try {
            List<FlowNodeVo> list = taskInfoMapper.getBackNode(processInstanceId);
            if (null != list && !list.isEmpty()) {
                //去重合并
                datas = list.stream().collect(
                        Collectors.collectingAndThen(Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(nodeVo -> nodeVo.getNodeId()))), ArrayList::new));
                //排序
                datas.sort(Comparator.comparing(FlowNodeVo::getEndTime));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>getBackNode error!", e);
            throw new MyException(CodeEnum.commonException);
        }
        return datas;
    }

    public void addNextTaskAssign(RequestVo requestVo) throws MyException {
        try {
            List<String> assignUsers = requestVo.getAssignUsers();
            List<String> assignGroups = requestVo.getAssignGroups();
            if (null != requestVo && (null != assignUsers && !assignUsers.isEmpty()) || (null != assignGroups && !assignGroups.isEmpty())) {
                String instanceId = requestVo.getProcessInstanceId();
                String businessKey = requestVo.getBusinessKey();
                if (StringUtils.isBlank(instanceId)) {
                    //根据业务主键查询流程实例主键
                    if (StringUtils.isNotBlank(businessKey)) {
                        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).orderByStartTime().desc().list().get(0);
                        if (null != instance) {
                            instanceId = instance.getProcessInstanceId();
                        } else {
                            throw new MyException(450, "查询流程实例失败！");
                        }
                    } else {
                        throw new MyException(CodeEnum.paramError);
                    }
                }
                if (StringUtils.isNotBlank(instanceId)) {
                    commonService.addAssignUserOrGroup(assignUsers, assignGroups, null, instanceId, null);
                } else {
                    throw new MyException(CodeEnum.paramError);
                }
            } else {
                throw new MyException(CodeEnum.paramError);
            }
        } catch (MyException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>addNextTaskAssign error!", e);
            throw new MyException(CodeEnum.commonException);
        }
    }

    public List<UserTaskVo> getProcessTasksByDefinitionKey(RequestVo request) throws MyException {
        try {
            String id = taskInfoMapper.getProcessDefinitionId(request.getProcessDefinitionKey());
            BpmnModel bpmnModel = repositoryService.getBpmnModel(id);
            Process process = bpmnModel.getProcesses().get(0);
            Collection<UserTask> flowElements = process.findFlowElementsOfType(UserTask.class);
            List<UserTask> userTasks = new ArrayList<>();
            Boolean isSort = true;
            for (UserTask task : flowElements) {
                userTasks.add(task);
                if (null == task.getPriority()) {
                    isSort = false;
                }
            }
            //排序
            if (isSort) {
                userTasks.sort(Comparator.comparing(UserTask::getPriority));
            }
            ProcessassignConfig conf = processassignConfigService.getLatestProcessAssignConf(request);
            Map<String, Map<String, List<String>>> configs = null;
            if (null != conf && null != conf.getConfigJson()) {
                configs = new Gson().fromJson(conf.getConfigJson(), Map.class);
            }
            List<UserTaskVo> list = new ArrayList<>();
            for (UserTask task : userTasks) {
                //添加任务节点，去除自审核任务节点
                if (!"submittercheck".equals(task.getId())) {
                    List<String> assignUsers = new ArrayList<>();
                    List<User> users = null;
                    List<User> lastUsers = null;
                    String assignee = task.getAssignee();
                    List<String> candidateUsers = task.getCandidateUsers();
                    if (null != assignee && !"".equals(assignee)) {
                        assignUsers.add(assignee);
                    }
                    if (null != candidateUsers && !candidateUsers.isEmpty()) {
                        assignUsers.addAll(candidateUsers);
                    }
                    if (!assignUsers.isEmpty()) {
                        users = userMapper.findUsersByIds(assignUsers);
                    }
                    //查询最近一次审核人员配置
                    List<String> lastUsersIds = null;
                    try {
                        Map<String, List<String>> stringListMap = configs.get(task.getId());
                        if (null != stringListMap) {
                            lastUsersIds = stringListMap.get("assignUsers");
                            if (null != lastUsersIds && !lastUsersIds.isEmpty()) {
                                lastUsers = userMapper.findUsersByIds(lastUsersIds);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    list.add(new UserTaskVo(task.getId(), task.getName(), users, lastUsers));
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>flowable get tasks by definitionKey error!", e);
            throw new MyException(CodeEnum.commonException);
        }
    }

    public void doNextTask(RequestVo requestVo) throws MyException {
        try {
            if (null != requestVo && StringUtils.isNotBlank(requestVo.getProcessDefinitionKey())) {
                String instanceId = null;
                if (StringUtils.isBlank(requestVo.getProcessInstanceId())) {
                    if (StringUtils.isNotBlank(requestVo.getBusinessKey())) {
                        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().processDefinitionKey(requestVo.getProcessDefinitionKey()).processInstanceBusinessKey(requestVo.getBusinessKey()).active().orderByStartTime().desc().list();
                        if (null != list && !list.isEmpty()) {
                            ProcessInstance processInstance = list.get(0);
                            instanceId = processInstance.getProcessInstanceId();
                        } else {
                            return;
                        }
                    } else {
                        throw new MyException(CodeEnum.paramError);
                    }
                } else {
                    instanceId = requestVo.getProcessInstanceId();
                }
                //查询下一任务
                Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
                if (null != task) {
                    requestVo.setIds(Arrays.asList(task.getId()));
                    //执行任务
                    doTask(requestVo);
                } else {
                    throw new MyException(409, "当前流程实例无正在运行任务！");
                }
            } else {
                throw new MyException(CodeEnum.paramError);
            }
        } catch (MyException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("doNextTaskByBusinessKey:{}", ExceptionUtils.getMessage(e));
            log.error("doNextTaskByBusinessKey:{}", e);
            log.error("===>doNextTaskByBusinessKey error!");
            throw new MyException(CodeEnum.commonException);
        }

    }

    public void complaintTask(RequestVo request) throws MyException {
        try {
            String taskId = request.getTaskId();
            String currentUserId = request.getCurrentUserId();
            String acceptUserId = request.getAcceptUserId();
            String acceptPersonName = request.getAcceptPersonName();
            String processInstanceId = request.getProcessInstanceId();
            String myMessage = request.getMessage();
            if (StringUtils.isNotBlank(taskId) && StringUtils.isNotBlank(currentUserId) && StringUtils.isNotBlank(acceptUserId) && StringUtils.isNotBlank(acceptPersonName)) {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                String definitionName = processInstance.getProcessDefinitionName();
                taskService.setOwner(taskId, currentUserId);
                taskService.deleteCandidateUser(taskId, currentUserId);
                taskService.addCandidateUser(taskId, acceptUserId);
                String message = "任务转发至:" + acceptPersonName;

                if (StringUtils.isNotBlank(myMessage)) {
                    message = message + "\n" + myMessage;
                }
                this.addComment(taskId, currentUserId, processInstanceId,
                        CommentTypeEnum.ZB.toString(), message);
                String sendMessage = "您有一条 " + definitionName + " 转办任务待处理!";
                //发送短信
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===>complaintTask error!");
            throw new MyException(CodeEnum.commonException);
        }
    }
}
